<template>
	<view class="competition-container">
		<!-- 头部搜索和筛选 -->
		<view class="header-section">
			<view class="search-bar">
				<uni-search-bar 
					v-model="searchText" 
					placeholder="搜索比赛名称、地点" 
					@confirm="onSearch"
					@clear="onSearchClear"
				></uni-search-bar>
			</view>
			
			<view class="filter-bar">
				<picker :value="filterIndex.type" :range="matchTypes" @change="onTypeChange">
					<view class="filter-item">
						{{ matchTypes[filterIndex.type] }}
						<uni-icons type="down" size="14" color="#666"></uni-icons>
					</view>
				</picker>
				
				<picker :value="filterIndex.level" :range="matchLevels" @change="onLevelChange">
					<view class="filter-item">
						{{ matchLevels[filterIndex.level] }}
						<uni-icons type="down" size="14" color="#666"></uni-icons>
					</view>
				</picker>
			</view>
		</view>

		<!-- 比赛列表 -->
		<view class="match-list">
			<view v-if="loading" class="loading-container">
				<uni-load-more status="loading"></uni-load-more>
			</view>
			
			<view v-else-if="matchList.length === 0" class="empty-container">
				<uni-icons type="info-filled" size="60" color="#ddd"></uni-icons>
				<text class="empty-text">暂无比赛信息</text>
				<text class="empty-tip">快去发布一场比赛吧</text>
			</view>
			
			<view v-else>
				<view 
					v-for="(match, index) in matchList" 
					:key="index" 
					class="match-item"
					:class="{ 'match-completed': match.computed_status === 'completed' }"
					@click="viewMatchDetail(match, index)"
				>
					<view class="match-header">
						<view class="match-title-section">
							<view class="match-title">{{ match.title }}</view>
							<!-- 新比赛/新日程徽章提醒 -->
							<view v-if="hasNewSchedules(match)" class="new-activity-badge">
								<view class="badge-dot"></view>
								<text class="badge-text">{{ getNewActivityText(match) }}</text>
							</view>
							<view class="match-type-tag">{{ getMatchTypeTag(match) }}</view>
							<!-- 已结束标签 -->
							<view v-if="match.computed_status === 'completed'" class="completed-tag">已结束</view>
						</view>
						<view class="match-status-section">
							<view class="match-status" :class="'status-' + match.computed_status">
								{{ getStatusText(match.computed_status) }}
							</view>
							<!-- 简单红点标记 -->
							<view v-if="hasNewSchedules(match)" class="new-schedule-dot"></view>
						</view>
					</view>
					
					<view class="match-basic-info">
						<!-- 时间信息 -->
						<view class="time-info">
							<uni-icons type="calendar" size="16" color="#666"></uni-icons>
							<text class="time-text">{{ formatDateRange(match.start_date, match.end_date) }}</text>
						</view>
						
						<!-- 地点信息 -->
						<view class="location-info">
							<uni-icons type="location" size="16" color="#666"></uni-icons>
							<text class="location-text">{{ match.location }}</text>
						</view>
					</view>
					
					<!-- 统计信息 -->
					<view class="match-stats">
						<view class="stat-item">
							<text class="stat-number total">{{ getMatchTotalGames(match) }}</text>
							<text class="stat-label">总场次</text>
						</view>
						<view class="stat-item">
							<text class="stat-number applications">{{ getMatchTotalApplications(match) }}</text>
							<text class="stat-label">总报名</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			loading: false,
			searchText: '',
			matchList: [],
			
			// 筛选条件
			filterIndex: {
				type: 0,
				level: 0
			},
			matchTypes: ['全部类型', '足球', '篮球', '排球', '羽毛球', '乒乓球', '网球', '其他'],
			matchLevels: ['全部级别', '校级', '区级', '市级', '省级', '国家级', '国际级']
		}
	},
	
	onLoad() {
		this.loadMatchList()
	},
	
	onPullDownRefresh() {
		this.loadMatchList().then(() => {
			uni.stopPullDownRefresh()
		})
	},
	
	onShow() {
		this.loadMatchList()
	},
	
	methods: {
		// 加载比赛列表
		async loadMatchList() {
			this.loading = true
			try {
				const matchObject = uniCloud.importObject('match-object')
				
				const params = {
					page: 1,
					limit: 20
				}
				
				// 添加筛选条件
				if (this.filterIndex.type > 0) {
					params.match_type = this.matchTypes[this.filterIndex.type]
				}
				if (this.filterIndex.level > 0) {
					params.level = this.matchLevels[this.filterIndex.level]
				}
				if (this.searchText.trim()) {
					params.search = this.searchText.trim()
				}
				
				const result = await matchObject.getMatchList(params)
				
				if (result.code === 0) {
					let matchList = result.data.list || []
					
					// 为每个比赛计算实际状态
					matchList = matchList.map(match => {
						return {
							...match,
							computed_status: this.computeMatchStatus(match)
						}
					})
					
					// 应用智能排序
					this.matchList = this.sortMatchList(matchList)
				} else {
					this.handleError(result.message || '获取失败')
				}
			} catch (error) {
				this.handleError('网络错误: ' + error.message)
			} finally {
				this.loading = false
			}
		},
		
		// 搜索
		onSearch() {
			this.loadMatchList()
		},
		
		onSearchClear() {
			this.searchText = ''
			this.loadMatchList()
		},
		
		// 筛选
		onTypeChange(e) {
			this.filterIndex.type = e.detail.value
			this.loadMatchList()
		},
		
		onLevelChange(e) {
			this.filterIndex.level = e.detail.value
			this.loadMatchList()
		},
		
		// 查看比赛详情
		viewMatchDetail(match, index) {
			if (!match && typeof index !== 'undefined') {
				match = this.matchList[index]
			}
			
			if (!match) {
				this.handleError('比赛数据错误')
				return
			}
			
			const matchId = match.id || match._id || match.match_id
			
			if (!matchId) {
				this.handleError('比赛ID不存在')
				return
			}
			
			// 清除新日程标记
			this.clearNewScheduleFlag(match)
			
			uni.navigateTo({
				url: `/packgeCompetition/competition/detail?id=${matchId}`
			})
		},
		
		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				draft: '草稿',
				published: '已发布',
				in_progress: '进行中',
				completed: '已完成',
				cancelled: '已取消'
			}
			return statusMap[status] || status
		},
		
		// 格式化日期范围
		formatDateRange(startDate, endDate) {
			if (!startDate) return ''
			
			const start = new Date(startDate)
			const end = endDate ? new Date(endDate) : null
			
			if (end && start.toDateString() !== end.toDateString()) {
				return `${start.getMonth() + 1}月${start.getDate()}日 - ${end.getMonth() + 1}月${end.getDate()}日`
			} else {
				return `${start.getMonth() + 1}月${start.getDate()}日`
			}
		},
		
		// 获取比赛类型标签
		getMatchTypeTag(match) {
			// 确保返回全汉字的赛制格式
			const format = match.match_format || '十一人制';
			
			// 统一转换为全汉字格式，防止数据中有数字+汉字的情况
			switch(format) {
				case '11人制':
				case '十一人制':
					return '十一人制';
				case '7人制':
				case '七人制':
					return '七人制';
				case '5人制':
				case '五人制':
					return '五人制';
				default:
					return format || '十一人制';
			}
		},
		
		// 获取比赛总场次（使用后端返回的真实数据）
		getMatchTotalGames(match) {
			return match.total_matches || 0
		},
		
		// 获取总报名数（使用后端返回的真实数据）
		getMatchTotalApplications(match) {
			return match.total_applications || 0
		},
		
		// 检查比赛是否有新日程或新活动
		hasNewSchedules(match) {
			// 优先使用后端返回的标记
			if (match.has_new_activity !== undefined) {
				return match.has_new_activity
			}
			
			// 检查后端返回的新活动标记
			if (match.hasNewActivity) {
				return true
			}
			
			// 检查是否有新日程标记
			if (match.newScheduleCount && match.newScheduleCount > 0) {
				return true
			}
			
			// 检查是否是最近发布的比赛（3天内创建的比赛视为新比赛）
			if (match.create_time) {
				const createTime = new Date(match.create_time)
				const now = new Date()
				const threeDaysAgo = new Date(now.getTime() - (3 * 24 * 60 * 60 * 1000))
				
				if (createTime > threeDaysAgo) {
					return true
				}
			}
			
			// 检查最后活动时间（如果是最近1天内有活动，显示红点）
			if (match.last_activity_time) {
				const lastActivity = new Date(match.last_activity_time)
				const now = new Date()
				const oneDayAgo = new Date(now.getTime() - (24 * 60 * 60 * 1000))
				
				if (lastActivity > oneDayAgo) {
					return true
				}
			}
			
			// 检查本地存储的查看状态
			try {
				const viewedKey = `viewed_match_${match._id || match.id}`
				const lastViewedTime = uni.getStorageSync(viewedKey)
				
				if (!lastViewedTime) {
					// 从未查看过，视为新比赛
					return true
				}
				
				if (lastViewedTime && match.update_time) {
					const lastViewed = new Date(lastViewedTime)
					const lastUpdate = new Date(match.update_time)
					
					// 如果最后更新时间晚于最后查看时间，显示新标记
					if (lastUpdate > lastViewed) {
						return true
					}
				}
			} catch (error) {
				console.error('检查查看状态失败:', error)
			}
			
			// 默认返回false
			return false
		},
		
		// 获取新活动提醒文本
		getNewActivityText(match) {
			// 检查是否有具体的新日程数量
			if (match.newScheduleCount && match.newScheduleCount > 0) {
				return `${match.newScheduleCount}场新日程`
			}
			
			// 检查是否是最近发布的比赛
			if (match.create_time) {
				const createTime = new Date(match.create_time)
				const now = new Date()
				const oneDayAgo = new Date(now.getTime() - (24 * 60 * 60 * 1000))
				
				if (createTime > oneDayAgo) {
					return '新比赛'
				}
			}
			
			// 检查是否有最近的活动
			if (match.last_activity_time) {
				const lastActivity = new Date(match.last_activity_time)
				const now = new Date()
				const oneDayAgo = new Date(now.getTime() - (24 * 60 * 60 * 1000))
				
				if (lastActivity > oneDayAgo) {
					return '有新动态'
				}
			}
			
			// 默认文本
			return '有更新'
		},
		
		// 清除新日程标记
		clearNewScheduleFlag(match) {
			try {
				// 立即更新本地显示
				if (match.has_new_activity !== undefined) {
					match.has_new_activity = false
				}
				if (match.hasNewActivity) {
					match.hasNewActivity = false
				}
				if (match.newScheduleCount) {
					match.newScheduleCount = 0
				}
				
				// 记录查看状态到本地存储
				const viewedKey = `viewed_match_${match._id || match.id}`
				const currentTime = new Date().toISOString()
				uni.setStorageSync(viewedKey, currentTime)
				
				console.log(`已记录比赛查看状态: ${viewedKey} = ${currentTime}`)
				
				// 注意：这里只进行本地状态更新，不调用后端API
				// 后端会在用户实际查看比赛详情时自动处理相关状态
			} catch (error) {
				console.error('清除新日程标记失败:', error)
				// 失败时不影响页面跳转
			}
		},
		
		// 计算比赛的实际状态
		computeMatchStatus(match) {
			// 检查是否有新日程活动
			const hasNewActivity = this.hasNewSchedules(match)
			
			// 检查比赛是否已结束
			// 简化判断：如果比赛结束日期已过且没有待处理事项，则认为已结束
			const isCompleted = this.isMatchCompleted(match)
			
			// 检查是否正在进行中
			const isInProgress = this.isMatchInProgress(match)
			
			if (isCompleted) {
				return 'completed'
			} else if (isInProgress) {
				return 'in_progress'
			} else {
				return match.status || 'published'
			}
		},
		
		// 判断比赛是否已完成
		isMatchCompleted(match) {
			// 如果原状态就是completed，直接返回true
			if (match.status === 'completed') {
				return true
			}
			
			// 如果比赛结束日期已过，进行进一步判断
			if (match.end_date) {
				const endDate = new Date(match.end_date)
				const now = new Date()
				
				// 结束日期已过
				if (endDate < now) {
					// 如果比赛结束超过3天，且没有新活动，认为已完成
					const daysPassed = (now - endDate) / (1000 * 60 * 60 * 24)
					if (daysPassed > 3 && !this.hasNewSchedules(match)) {
						return true
					}
					
					// 如果有场次但长时间没有新的报名活动，可能已完成
					if (match.total_matches > 0 && !this.hasNewSchedules(match) && daysPassed > 1) {
						return true
					}
				}
			}
			
			return false
		},
		
		// 判断比赛是否正在进行中
		isMatchInProgress(match) {
			if (match.status === 'in_progress') {
				return true
			}
			
			// 如果比赛已发布，在进行时间范围内，且有活动，则认为正在进行
			if (match.status === 'published' && match.start_date && match.end_date) {
				const startDate = new Date(match.start_date)
				const endDate = new Date(match.end_date)
				const now = new Date()
				
				// 在比赛时间范围内，且有场次或报名活动
				if (now >= startDate && now <= endDate) {
					if (match.total_matches > 0 || match.total_applications > 0) {
						return true
					}
				}
			}
			
			return false
		},
		
		// 智能排序比赛列表
		sortMatchList(matchList) {
			return matchList.sort((a, b) => {
				// 第一优先级：有新日程的比赛置顶
				const aHasNew = this.hasNewSchedules(a)
				const bHasNew = this.hasNewSchedules(b)
				
				if (aHasNew && !bHasNew) return -1
				if (!aHasNew && bHasNew) return 1
				
				// 第二优先级：按状态排序
				const aStatus = a.computed_status
				const bStatus = b.computed_status
				
				// 状态权重：进行中 > 已发布 > 草稿 > 已完成 > 已取消
				const statusWeight = {
					'in_progress': 4,
					'published': 3,
					'draft': 2,
					'completed': 1,
					'cancelled': 0
				}
				
				const aWeight = statusWeight[aStatus] || 2
				const bWeight = statusWeight[bStatus] || 2
				
				if (aWeight !== bWeight) {
					return bWeight - aWeight // 降序，权重高的在前
				}
				
				// 第三优先级：同等状态下按创建时间排序（新的在前）
				const aTime = new Date(a.create_time || a.update_time || 0)
				const bTime = new Date(b.create_time || b.update_time || 0)
				
				return bTime - aTime
			})
		},
		
		// 错误处理
		handleError(message) {
			uni.showToast({
				title: message,
				icon: 'none'
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.competition-container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.header-section {
	background-color: #fff;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.search-bar {
	margin-bottom: 20rpx;
}

.filter-bar {
	display: flex;
	gap: 20rpx;
}

.filter-item {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 16rpx 24rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #666;
}

.match-list {
	padding: 0 20rpx;
}

.loading-container,
.empty-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-text {
	margin-top: 20rpx;
	font-size: 28rpx;
	color: #999;
}

.empty-tip {
	margin-top: 10rpx;
	font-size: 24rpx;
	color: #ccc;
}

.match-item {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 0;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	border-left: 8rpx solid #007aff;
	overflow: hidden;
	position: relative;
}

.match-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 20rpx;
	padding: 30rpx 30rpx 0 30rpx;
}

.match-title-section {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	gap: 12rpx;
}

.match-title {
	flex: 1;
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	line-height: 1.4;
}

.match-type-tag {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	color: #fff;
	background-color: #1BAE76;
	margin-left: 20rpx;
}

.match-status-section {
	display: flex;
	align-items: center;
}

.match-status {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	color: #fff;
	margin-left: 20rpx;
	
	&.status-draft {
		background-color: #999;
	}
	
	&.status-published {
		background-color: #1BAE76;
	}
	
	&.status-in_progress {
		background-color: #ff9500;
	}
	
	&.status-completed {
		background-color: #007aff;
	}
	
	&.status-cancelled {
		background-color: #ff3b30;
	}
}

.match-basic-info {
	margin-bottom: 30rpx;
	padding: 0 30rpx;
}

.time-info,
.location-info {
	display: flex;
	align-items: center;
	margin-bottom: 12rpx;
}

.time-text,
.location-text {
	margin-left: 12rpx;
	font-size: 26rpx;
	color: #666;
}

.match-stats {
	display: flex;
	justify-content: space-around;
	background-color: #f8f9fa;
	padding: 20rpx 0;
	margin-top: 20rpx;
}

.stat-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	flex: 1;
}

.stat-number {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 8rpx;
	
	&.total {
		color: #007aff;
	}
	
	&.applications {
		color: #1BAE76;
	}
}

.stat-label {
	font-size: 24rpx;
	color: #6c757d;
}

.new-schedule-dot {
	width: 16rpx;
	height: 16rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #ff3b30 0%, #ff6347 100%);
	margin-left: 8rpx;
	animation: dot-pulse 1.5s infinite;
	box-shadow: 0 0 0 4rpx rgba(255, 59, 48, 0.2);
	border: 2rpx solid #fff;
}

/* 红点动画效果 */
@keyframes dot-pulse {
	0% {
		transform: scale(1);
		opacity: 1;
	}
	50% {
		transform: scale(1.2);
		opacity: 0.7;
	}
	100% {
		transform: scale(1);
		opacity: 1;
	}
}

/* 徽章脉冲动画 */
@keyframes badge-pulse {
	0% {
		transform: scale(1);
		box-shadow: 0 2rpx 8rpx rgba(255, 59, 48, 0.3);
	}
	50% {
		transform: scale(1.05);
		box-shadow: 0 4rpx 16rpx rgba(255, 59, 48, 0.5);
	}
	100% {
		transform: scale(1);
		box-shadow: 0 2rpx 8rpx rgba(255, 59, 48, 0.3);
	}
}

/* 徽章内小点闪烁动画 */
@keyframes dot-blink {
	0% {
		opacity: 1;
	}
	50% {
		opacity: 0.5;
	}
	100% {
		opacity: 1;
	}
}

/* 已结束比赛样式 */
.match-completed {
	opacity: 0.7;
	filter: grayscale(0.3);
	position: relative;
	
	&::after {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.05);
		pointer-events: none;
		border-radius: 16rpx;
	}
	
	.match-title {
		color: #888 !important;
	}
	
	.time-text,
	.location-text {
		color: #999 !important;
	}
	
	.stat-number {
		color: #aaa !important;
	}
}

/* 已结束标签 */
.completed-tag {
	padding: 8rpx 16rpx;
	border-radius: 12rpx;
	font-size: 22rpx;
	color: #fff;
	background: linear-gradient(135deg, #8E8E93 0%, #6C6C70 100%);
	font-weight: 600;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
	border: 1rpx solid rgba(255, 255, 255, 0.2);
}

/* 新比赛/新日程徽章提醒 */
.new-activity-badge {
	display: flex;
	align-items: center;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 22rpx;
	color: #fff;
	background: linear-gradient(135deg, #ff3b30 0%, #ff6347 100%);
	margin-left: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(255, 59, 48, 0.3);
	animation: badge-pulse 2s infinite;
}

.badge-dot {
	width: 8rpx;
	height: 8rpx;
	border-radius: 50%;
	background-color: #fff;
	margin-right: 6rpx;
	animation: dot-blink 1.5s infinite;
}

.badge-text {
	font-size: 22rpx;
	font-weight: 600;
	letter-spacing: 0.5rpx;
}
</style> 